package com.ars.common.servlet;

import com.ars.common.dao.submitMaterialsMysql;
import com.ars.common.beans.User.User;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


/*
 * 提交活动材料，写入文件
 * @auther:liwentao
 * @date:2020/12/01
 * */
@WebServlet("/submitActiveMat")
@MultipartConfig
public class submitActiveMat extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User LogUser = (User) request.getSession().getAttribute("LogUser");
        System.out.println(LogUser);
        String UserID = LogUser.getUserID();
        String ActiveID = request.getParameter("ActiveID");
        System.out.println(ActiveID);

        Part filePart = request.getPart("image");
        if (filePart == null) {
            response.getWriter().println("未能获取上传的文件部分");
            return;
        }

        String fileName = getFileName(filePart);
        if (fileName == null || fileName.isEmpty()) {
            response.getWriter().println("无法提取文件名");
            return;
        }

        String fileExtension = fileName.substring(fileName.lastIndexOf("."));

        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String formattedTime = currentTime.format(formatter);

        // 生成新的文件名
        String newFileName = formattedTime + "_" + UserID + fileExtension;

        // 获取ServletContext来构建服务器路径
        ServletContext context = request.getServletContext();
        String uploadDirectory = context.getRealPath("/images" + "/" + ActiveID);

        File uploadDir = new File(uploadDirectory);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        String filePath = uploadDirectory + File.separator + newFileName;
        System.out.println(filePath);

        try (OutputStream out = new FileOutputStream(filePath);
             InputStream fileContent = filePart.getInputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fileContent.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 输出格式化后的时间字符串
        System.out.println("Formatted DateTime: " + formattedTime);

        // 将新的文件名存入数据库
        try {
            submitMaterialsMysql.submit(ActiveID, UserID, newFileName);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        response.getWriter().println("图片上传成功: " + newFileName);
    }

    private String getFileName(Part part) {
        String contentDisposition = part.getHeader("content-disposition");
        for (String cd : contentDisposition.split(";")) {
            if (cd.trim().startsWith("filename")) {
                return cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }

}